﻿function Soap(webservice) {
    this.webservice_ = webservice;
    this.header_ = '<?xml version="1.0" encoding="utf-8"?> \
                        <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> \n \
                            <soap:Body> \n';
    this.footer_ = '</soap:Body> \n \
                      </soap:Envelope>';

    var me = this;
    this.setNamespace_ = function (ns) {
        this.ns_ = ns || ns_;
    };

    this.getNamespace = function () {
        return this.ns_ || 'http://real-hanhud.com/WebService';
    };
}

Soap.prototype.send = function (methodName, params, callback) {
    var me = this;
    $.ajax({
        type: 'POST',
        dataType: 'xml',
        url: me.webservice_,
        data: me.getSoapRequest_(methodName, params),
        contentType: Soap.SOAP_CONTENT_TYPE,
        beforeSend: function (xhr) {
            if (IEBrowser) {
                xhr.setRequestHeader('Content-Type', Soap.SOAP_CONTENT_TYPE);
            }
        },
        success: function (result, status) {
            if (callback && typeof (callback) == 'function') {
                var $collection = $(result).find(methodName + 'Response > ' + methodName + 'Result');
                callback($collection);
            }
        },
        error: function (xhr, msg) {
            alert(xhr.statusText);
        }
    });
};

Soap.prototype.getSoapRequest_ = function (methodName, params) {
    var me = this;
    var request = me.getHeader();
    request = request.concat('<').concat(methodName).concat(' xmlns="' + me.getNamespace() + '"> \n');
    if (params) {
        for (var name in params) {
            if (params.hasOwnProperty(name)) {
                request = request.concat('<').concat(name).concat('>').concat(params[name]).concat('</').concat(name).concat('>');
            }
        }
    }
    request = request.concat('</').concat(methodName).concat('> \n').concat(me.getFooter());

    return request;
};

Soap.prototype.getHeader = function () {
    return this.header_;
};

Soap.prototype.getFooter = function () {
    return this.footer_;
};

Soap.SOAP_CONTENT_TYPE = 'text/xml; charset=utf-8'; //(SOAP 1.1)  //'application/soap+xml; charset=utf-8';(SOAP 1.2)